//
//  Button.swift
//  Box
//
//  Created by mn on 2025/3/30.
//

import UIKit
import ObjectiveC

private var ActionBlockKey: UInt8 = 0

extension UIButton {
    typealias ButtonAction = () -> Void

    private var actionBlock: ButtonAction? {
        get {
            return objc_getAssociatedObject(self, &ActionBlockKey) as? ButtonAction
        }
        set {
            objc_setAssociatedObject(self, &ActionBlockKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    func addAction(for event: UIControl.Event = .touchUpInside, action: @escaping ButtonAction) {
        actionBlock = action
        addTarget(self, action: #selector(handleAction), for: event)
    }

    @objc private func handleAction() {
        actionBlock?()
    }
}
